import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:free_music_player/providers/music_provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:free_music_player/constants/api_constants.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_xlider/flutter_xlider.dart';

class PlayingScreen extends StatefulWidget {
  const PlayingScreen({super.key});

  @override
  State<PlayingScreen> createState() => _PlayingScreenState();
}

class _PlayingScreenState extends State<PlayingScreen> {
  String _lyric = '';
  bool _isLoadingLyric = false;
  int _currentPosition = 0;
  List<LyricLine> _lyricLines = [];
  int _currentLyricIndex = -1;

  @override
  void initState() {
    super.initState();
    _loadLyric();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 监听歌曲变化
    Provider.of<MusicProvider>(context, listen: false)
        .addListener(_onMusicChanged);
  }

  @override
  void dispose() {
    Provider.of<MusicProvider>(context, listen: false)
        .removeListener(_onMusicChanged);
    super.dispose();
  }

  void _onMusicChanged() {
    // 当歌曲变化时重新加载歌词
    _loadLyric();
  }

  Future<void> _loadLyric() async {
    final provider = Provider.of<MusicProvider>(context, listen: false);
    if (provider.currentSong == null) return;

    setState(() {
      _isLoadingLyric = true;
      _lyric = '';
      _lyricLines = [];
      _currentLyricIndex = -1;
    });

    try {
      String lyric = await provider.getLyric(provider.currentSong!.id);
      setState(() {
        _lyric = lyric;
        _parseLyric(lyric);
        _isLoadingLyric = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingLyric = false;
        _lyric = '获取歌词失败';
      });
    }
  }

  void _parseLyric(String lyric) {
    List<LyricLine> lines = [];
    RegExp reg = RegExp(r'\[(\d+):(\d+).(\d+)\](.*)');

    for (String line in lyric.split('\n')) {
      Match? match = reg.firstMatch(line);
      if (match != null) {
        int minute = int.parse(match.group(1)!);
        int second = int.parse(match.group(2)!);
        int millisecond = int.parse(match.group(3)!);
        String text = match.group(4)!;

        int time = minute * 60 * 1000 + second * 1000 + millisecond * 10;
        lines.add(LyricLine(time, text));
      }
    }

    // 按时间排序
    lines.sort((a, b) => a.time.compareTo(b.time));
    setState(() {
      _lyricLines = lines;
    });
  }

  void _updateCurrentLyricIndex(int position) {
    setState(() {
      _currentPosition = position;

      // 找到当前播放位置对应的歌词
      for (int i = _lyricLines.length - 1; i >= 0; i--) {
        if (_lyricLines[i].time <= position) {
          if (_currentLyricIndex != i) {
            _currentLyricIndex = i;
          }
          break;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicProvider>(
      builder: (context, provider, child) {
        if (provider.currentSong == null) {
          return const Scaffold(
            body: Center(child: Text('没有正在播放的歌曲')),
          );
        }

        final song = provider.currentSong!;

        return Scaffold(
          appBar: AppBar(
            title: const Text('正在播放'),
          ),
          body: Column(
            children: [
              // 专辑封面
              Expanded(
                flex: 2,
                child: Center(
                  child: Container(
                    margin: const EdgeInsets.all(20),
                    width: MediaQuery.of(context).size.width * 0.7,
                    height: MediaQuery.of(context).size.width * 0.7,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.2),
                          blurRadius: 10,
                          offset: const Offset(0, 5),
                        ),
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(20),
                      child: CachedNetworkImage(
                        imageUrl: song.album.picUrl,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => const
                            CircularProgressIndicator(),
                        errorWidget: (context, url, error) =>
                            const Icon(Icons.music_note, size: 50),
                      ),
                    ),
                  ),
                ),
              ),

              // 歌曲信息
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Text(
                      song.name,
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 8),
                    Text(
                      song.artistsName,
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey[600],
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),

              // 进度条
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          _formatDuration(_currentPosition),
                          style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                        ),
                        Text(
                          song.formattedDuration,
                          style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                        ),
                      ],
                    ),
                    FlutterSlider(
                      values: [_currentPosition.toDouble()],
                      max: song.duration.toDouble(),
                      onDragging: (handlerIndex, lowerValue, upperValue) {
                        _updateCurrentLyricIndex(lowerValue.toInt());
                      },
                      onDragCompleted: (handlerIndex, lowerValue, upperValue) {
                        // 这里可以添加 seek 功能
                      },
                    ),
                  ],
                ),
              ),

              // 播放控制
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // 播放模式
                    IconButton(
                      icon: Icon(
                        provider.playMode == AppConstants.playModeSequence
                            ? Icons.repeat
                            : provider.playMode == AppConstants.playModeRandom
                                ? Icons.shuffle
                                : Icons.repeat_one, 
                        size: 24,
                      ),
                      onPressed: () {
                        provider.togglePlayMode();
                      },
                    ),

                    // 上一首
                    IconButton(
                      icon: const Icon(Icons.skip_previous, size: 32),
                      onPressed: () {
                        provider.previousSong();
                      },
                    ),

                    // 播放/暂停
                    IconButton(
                      icon: Icon(
                        provider.isPlaying ? Icons.pause : Icons.play_arrow,
                        size: 40,
                      ),
                      onPressed: () {
                        if (provider.isPlaying) {
                          provider.pause();
                        } else {
                          provider.resume();
                        }
                      },
                    ),

                    // 下一首
                    IconButton(
                      icon: const Icon(Icons.skip_next, size: 32),
                      onPressed: () {
                        provider.nextSong();
                      },
                    ),

                    // 更多选项
                    IconButton(
                      icon: const Icon(Icons.more_horiz, size: 24),
                      onPressed: () {
                        // 这里可以添加更多选项功能
                      },
                    ),
                  ],
                ),
              ),

              // 歌词区域
              Expanded(
                flex: 1,
                child: _isLoadingLyric
                    ? const Center(child: CircularProgressIndicator())
                    : _lyricLines.isEmpty
                        ? Center(child: Text(_lyric))
                        : ListView.builder(
                            itemCount: _lyricLines.length,
                            itemBuilder: (context, index) {
                              final line = _lyricLines[index];
                              return Center(
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 8.0),
                                  child: Text(
                                    line.text,
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: index == _currentLyricIndex
                                          ? Colors.blue
                                          : Colors.grey[600],
                                      fontWeight: index == _currentLyricIndex
                                          ? FontWeight.bold
                                          : FontWeight.normal,
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
              ),
            ],
          ),
        );
      },
    );
  }

  String _formatDuration(int milliseconds) {
    int seconds = milliseconds ~/ 1000;
    int minutes = seconds ~/ 60;
    seconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
}

class LyricLine {
  final int time;
  final String text;

  LyricLine(this.time, this.text);
}